#include "func.h"
#define DEBUG 1

int main(int argc,char *argv[])
{
    ARGS_CHECK(argc,3);
    int sock_fd=socket(AF_INET,SOCK_DGRAM,0);
    ERROR_CHECK(sock_fd,-1,"sock_fd");
    int ret;
    struct sockaddr_in serAddr;
    memset(&serAddr,0,sizeof(serAddr));
    serAddr.sin_family=AF_INET;
    serAddr.sin_addr.s_addr=inet_addr(argv[1]);
    serAddr.sin_port=htons(atoi(argv[2]));
    ret=bind(sock_fd,(struct sockaddr *)&serAddr,sizeof(serAddr));
    ERROR_CHECK(ret,-1,"bind");

    struct sockaddr_in clientAddr;
    int addrLen=sizeof(clientAddr);
    char buf[1000]={0};
    //必须使用recvfrom,存储好发送方的信息、udp必须客户端先发送信息
    recvfrom(sock_fd,buf,sizeof(buf),0,(struct sockaddr *)&clientAddr,&addrLen);
    ERROR_CHECK(ret,-1,"recvfrom");
    printf("%s\n",buf);
    fd_set rdset;
    while(1)
    {
        FD_ZERO(&rdset);
        FD_SET(STDIN_FILENO,&rdset);
        FD_SET(sock_fd,&rdset);
        select(sock_fd+1,&rdset,NULL,NULL,NULL);
        if(FD_ISSET(STDIN_FILENO,&rdset))
        {
            memset(buf,0,sizeof(buf));
            read(STDIN_FILENO,buf,sizeof(buf));
            sendto(sock_fd,buf,strlen(buf)-1,0,(struct sockaddr*)&clientAddr,sizeof(clientAddr));            
        }
        if(FD_ISSET(sock_fd,&rdset))
        {
            memset(buf,0,sizeof(buf));
            recvfrom(sock_fd,buf,sizeof(buf),0,NULL,NULL);
            printf("%s\n",buf);
        }
    }
    return 0;
}